import { Tabs, DatePicker, Card, Select, Descriptions, Pagination } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { history } from "umi";
import { useEffect, useState } from "react";
import { PaddingContent } from "@/components/page-padding";
import { CustomTitle } from "@/components/customTitle";
import { StyledAddBtn } from "@/components/button";
import BookingRecord from "@/components/booking-record";
import "./index.less";
import userStore from "@/store/userStore";
import { getBookingList, BookingListReqParams } from "@/services/booking";
import { BookingDataRes } from "@/components/booking-record/types";
import type { Dayjs } from "dayjs";
export type NoUndefinedRangeValueType<DateType> = [
  start: DateType | null,
  end: DateType | null
];

export type RangeValueType<DateType> = [
  start: DateType | null | undefined,
  end: DateType | null | undefined
];

const { RangePicker } = DatePicker;

const MyBookingRecords = () => {
  //const [bookingData] = useState<BookingDataRes[]>([]);
  // // todo 先造数据
  // bookingData: any[] = [
  //   {
  //     carParkEnName: "carParkEnName",
  //     carParkChnName: "carParkChnName",
  //     passType: "Monthly",
  //     vehType: "Private Car",
  //     price: "HK$2,000",
  //     lpnNo: "AC123",
  //     octopus: "70000111",
  //     bookingStatus: "Successful",
  //     bookingId: "0000001",
  //     startDate: "1/10/2024",
  //     endDate: "31/10/2024",
  //     pymPrice: "HK$1,000",
  //   },
  // ];

  const { userId } = userStore();
  const [vehType, setVehType] = useState<string | null>();
  const [parkingStatus, setParkingStatus] = useState<string | null>();
  const [sellectDates, setSellectDates] =
    useState<RangeValueType<Dayjs> | null>();
  const [bookingData, setBookingData] = useState<BookingDataRes[]>([]);
  const [reqParams, setReqParams] = useState<BookingListReqParams>({
    userId: null,
    passType: null,
    vehType: null,
    parkingStatus: null,
    startDate: null,
    endDate: null,
    pageNumber: null,
    pageSize: null,
  });

  const [paginationData, setPaginationData] = useState({
    pageNumber: undefined,
    pageSize: undefined,
    totalSize: undefined,
    totalPage: undefined,
    pageRecord: undefined,
  });

  const getBookingListMethod = (reqParams: BookingListReqParams) => {
    getBookingList({
      //userId: userId,
      userId: "1badec03-77f7-43be-9ed3-dd37a4ea5a6c",
      passType: reqParams.passType,
      vehType: reqParams.vehType,
      parkingStatus: reqParams.parkingStatus,
      startDate: reqParams.startDate,
      endDate: reqParams.endDate,
      pageNumber: reqParams.pageNumber,
      pageSize: reqParams.pageSize,
    })
      .then((data) => {
        //@ts-ignore
        if (data.code === 200) {
          console.log(data, "getBookingList");
        }
        //@ts-ignore
        setBookingData(data.data.content);
        //@ts-ignore
        setPaginationData(data.data);
      })
      .catch((error) => {
        setBookingData([]);
        console.error(error, "error");
      });
  };

  useEffect(() => {
    const updateParams = async () => {
      const newParams = {
        ...reqParams,
        // userId: "1badec03-77f7-43be-9ed3-dd37a4ea5a6c",
        userId: userId,
        pageNumber: 1,
        pageSize: 10,
      };
      setReqParams(newParams);
      console.log("useEffect newParams==", newParams);
      await getBookingListMethod(newParams);
    };
    updateParams();
  }, []);

  const onChangeDate = (
    dates: NoUndefinedRangeValueType<Dayjs> | null,
    dateStrings: [string, string]
  ) => {
    console.log("Selected date:", dates);
    console.log("Date string:", dateStrings);
    const newParams = {
      ...reqParams,
      startDate: dateStrings[0],
      endDate: dateStrings[1],
    };
    setSellectDates(dates);
    setReqParams(newParams);
    getBookingListMethod(newParams);
  };

  const handleChangeStatus = async (value: string) => {
    console.log("handleChangeStatus value:", value);
    const newParams = {
      ...reqParams,
      parkingStatus: value,
    };
    setParkingStatus(value);
    setReqParams(newParams);
    getBookingListMethod(newParams);
  };
  const handleChangeVehType = async (value: string) => {
    console.log("handleChangeVehType value:", value);
    const newParams = {
      ...reqParams,
      vehType: value,
    };
    setVehType(value);
    setReqParams(newParams);
    getBookingListMethod(newParams);
  };

  const onChangeTabs = (key: string) => {
    setParkingStatus(null);
    setVehType(null);
    setSellectDates(null);
    if (key === "All") {
      const newParams = {
        ...reqParams,
        passType: null,
        endDate: null,
        startDate: null,
        vehType: null,
        parkingStatus: null,
      };
      setReqParams(newParams);
      getBookingListMethod(newParams);
    } else if (key === "Monthly") {
      const newParams = {
        ...reqParams,
        passType: "Monthly",
        endDate: null,
        startDate: null,
        vehType: null,
        parkingStatus: null,
      };
      setReqParams(newParams);
      getBookingListMethod(newParams);
    } else if (key === "Daily") {
      const newParams = {
        ...reqParams,
        passType: "Daily",
        endDate: null,
        startDate: null,
        vehType: null,
        parkingStatus: null,
      };
      setReqParams(newParams);
      getBookingListMethod(newParams);
    }
  };

  const tab = (
    <>
      <Card style={{ backgroundColor: "#F7F5F1" }}>
        <Descriptions layout="vertical">
          <Descriptions.Item label="Parking Period">
            {/* <DatePicker
              style={{ width: 240 }}
              placeholder="select Date"
              format={{
                format: "YYYY-MM-DD",
                type: "mask",
              }}
              onChange={onChange}
            /> */}

            <RangePicker
              value={sellectDates}
              size="middle"
              placeholder={["Select Start Date Range", "Select End Date Range"]}
              placement="bottomLeft"
              onChange={onChangeDate}
            />
          </Descriptions.Item>
          <Descriptions.Item label="Parking Status">
            <Select
              value={parkingStatus}
              defaultValue={null}
              style={{ width: 240 }}
              onChange={handleChangeStatus}
              options={[
                { value: null, label: "All" },
                { value: "REGISTER", label: "Register" },
                { value: "SUCCESS", label: "Success" },
                { value: "WAIT_LIST", label: "WaitList" },
                { value: "EXPIRED", label: " Expired" },
                { value: "CANCEL", label: "Cancel" },
              ]}
            />
          </Descriptions.Item>
          <Descriptions.Item label="Vehicle Type">
            <Select
              value={vehType}
              defaultValue={null}
              style={{ width: 240 }}
              autoClearSearchValue={true}
              onChange={handleChangeVehType}
              options={[
                { value: null, label: "All" },
                { value: "PRIVATE_CAR", label: "Private Car" },
                { value: "MOTOR_CYCLE", label: "Motor Cycle" },
                { value: "LVG", label: "Large Good Vehicle" },
              ]}
            />
          </Descriptions.Item>
        </Descriptions>
      </Card>
      <BookingRecord bookingDataRes={bookingData} />
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <span> Total {paginationData.totalSize} items</span>
        <Pagination
          total={paginationData.totalSize}
          defaultCurrent={1}
          showSizeChanger
          //showQuickJumpe
          showTitle={false}
          align="end"
          onChange={(page, pageSize) => {
            const newParams = {
              ...reqParams,
              pageNumber: page,
              pageSize: pageSize,
            };
            setReqParams(newParams);
            getBookingListMethod(newParams);
          }}
        />
      </div>
    </>
  );
  return (
    <PaddingContent>
      <div className="myBookingRecords-containery">
        <div className="top-content">
          <CustomTitle>My Booking Records </CustomTitle>
          <StyledAddBtn
            style={{ margin: "7px 0" }}
            icon={<PlusOutlined />}
            onClick={() => history.push("/")}
            type="default"
            size={"middle"}
          >
            Car Park Booking
          </StyledAddBtn>
        </div>
        <Tabs
          onChange={onChangeTabs}
          defaultActiveKey="1"
          className="custom-tab-bar-gutter"
          indicator={{ size: 120, align: "center" }}
          size="large"
          items={[
            {
              label: <span className="all-tab">All</span>,
              key: "All",
              children: tab,
            },
            {
              label: <span className="all-tab">Daily</span>,
              key: "Daily",
              children: tab,
            },
            {
              label: <span className="all-tab">Monthly</span>,
              key: "Monthly",
              children: tab,
            },
          ]}
        />
      </div>
    </PaddingContent>
  );
};

export default MyBookingRecords;
